package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gowork_0911/gym/basic/config"
	"gowork_0911/gym/handler/model"
	"gowork_0911/gym/jwt"
	"strconv"

	"gowork_0911/gym/handler/request"
	"net/http"
)

func CourseAdd(c *gin.Context) {
	var form request.CourseAdd
	// 根据 Content-Type Header 推断使用哪个绑定器。
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var course model.Course
	if course.ID > 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "课程已存在",
		})
		return
	}
	fmt.Println(c.GetString("userId"))
	userId := c.GetString("userId")
	id, _ := strconv.Atoi(userId)

	if id == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "userId不存在",
		})
		return
	}

	course.UserId = id
	course.Name = form.Name
	course.Next = form.Next
	err := course.CourseAdd(config.DB)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "课程添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 400,
		"msg":  "课程添加成功",
	})
	return
}

func Login(c *gin.Context) {
	var form request.Login
	// 根据 Content-Type Header 推断使用哪个绑定器。
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var user model.User
	if err := config.DB.Where("user_name = ?", form.UserName).First(&user).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != form.Password {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "用户登录失败,密码不正确",
		})
		return
	}
	token, err := jwt.GetJwtToken(strconv.Itoa(int(user.ID)))
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 400,
		"msg":  "课程删除成功",
		"data": token,
	})
	return
}
